﻿using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Newtonsoft.Json;
using OpcUaHelper;
using RestSharp;
using Configuration.ServerApi.Param;
using System;
using System.Threading.Tasks;

namespace Configuration.ServerApi.Service.Impl
{
    /// <summary>
    /// BigModelService
    /// </summary>
    public class BigModelService : IBigModelService
    {
        private readonly IConfiguration Configuration;
        private readonly IHttpContextAccessor Accessor;

        #region 构造函数

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="configuration"></param>
        /// <param name="accessor"></param>
        public BigModelService(IConfiguration configuration,
            IHttpContextAccessor accessor)
        {
            Configuration = configuration;
            Accessor = accessor;
        }

        #endregion 构造函数

        #region 公共方法

        /// <summary>
        /// 使用 AK，SK 生成鉴权签名（Access Token）
        /// </summary>
        /// <returns>鉴权签名信息（Access Token）</returns>
        public string GetAccessToken()
        {
            var client = new RestClient($"https://aip.baidubce.com/oauth/2.0/token") { Timeout = -1 };
            var request = new RestRequest(Method.POST);
            request.AddParameter("grant_type", "client_credentials");
            request.AddParameter("client_id", $"{Configuration["BaiduApiConfig:ApiKey"]}");
            request.AddParameter("client_secret", $"{Configuration["BaiduApiConfig:SecretKey"]}");
            IRestResponse response = client.Execute(request);
            Console.WriteLine(response.Content);
            var result = JsonConvert.DeserializeObject<dynamic>(response.Content);
            return result.access_token.ToString();
        }

        #endregion

        #region 返回实体

        /// <summary>
        /// BaiduSpeechApiResultModel
        /// </summary>
        public class BaiduSpeechApiResultModel
        {
            /// <summary>
            /// corpus_no
            /// </summary>
            public string corpus_no { get; set; }

            /// <summary>
            /// err_msg
            /// </summary>
            public string err_msg { get; set; }

            /// <summary>
            /// err_no
            /// </summary>
            public int err_no { get; set; }

            /// <summary>
            /// result
            /// </summary>
            public string[] result { get; set; }

            /// <summary>
            /// result_data
            /// </summary>
            public string result_data { get; set; }

            /// <summary>
            /// sn
            /// </summary>
            public string sn { get; set; }
        }

        #endregion

        #region 获取百度API服务的Token

        /// <summary>
        /// 获取百度API服务的Token
        /// </summary>
        /// <returns>JSON结果集</returns>
        public async Task<JsonResult> BaiduAccessToken()
        {
            await Task.Run(() => { Console.WriteLine("\n获取百度API服务的Token：BaiduAccessToken"); });

            return new JsonResult(new ResultModel
            {
                Data = GetAccessToken(),
            });
        }

        #endregion

        #region 百度语音转文字

        /// <summary>
        /// 百度语音转文字
        /// </summary>
        /// <param name="param">搜索条件</param>
        /// <returns>JSON结果集</returns>
        public async Task<JsonResult> BaiduSpeechToText(SearchModel param)
        {
            await Task.Run(() => { Console.WriteLine("\n百度语音转文字：BaiduSpeechToText"); });

            #region 参数、数据校验

            //Console.WriteLine($"Speech：{param.Speech}");
            Console.WriteLine($"Length：{param.Length}");

            #endregion 

            var client = new RestClient($"https://vop.baidu.com/server_api") { Timeout = -1 };
            var request = new RestRequest(Method.POST);
            request.AddHeader("Content-Type", "application/json");
            request.AddHeader("Accept", "application/json");
            var body = JsonConvert.SerializeObject(new
            {
                format = "pcm",
                rate = 16000,
                channel = 1,
                cuid = TextHelper.GetRnd(30),
                dev_pid = 1537,
                speech = param.Speech,
                len = param.Length,
                token = GetAccessToken()
            });
            request.AddParameter("application/json", body, ParameterType.RequestBody);
            IRestResponse response = client.Execute(request);
            Console.WriteLine(response.Content);

            BaiduSpeechApiResultModel result = JsonConvert.DeserializeObject<BaiduSpeechApiResultModel>(response.Content);
            try
            {
                result.result_data = string.Join("", result.result);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
            }

            return new JsonResult(new ResultModel
            {
                Data = result,
            });
        }

        #endregion

    }
}